<template>
    <el-card class="box-card">

        <header>
            <div class="header_left">
                <el-button type="primary" @click="dialogVisible = true">新增</el-button>
                <el-button @click="del">删除</el-button>
            </div>
            <div class="header_right">
                <el-input v-model="input" placeholder="输入关键字" clearable style="width: 10rem;" />

                <el-button type="primary" :icon="Search" @click="searchvalue">查询</el-button>
                <el-button :icon="RefreshLeft" @click="cz">重置</el-button>
            </div>
        </header>
        <el-table :data="newdata" stripe style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection">
            </el-table-column>
            <el-table-column label="版本缩略图">
                <template #default="scope">
                    <div class="demo-image__preview" v-if="scope.row.verThumbnail">
                        <div class="images">
                            <el-image :z-index="990000" style="width: 5rem; height: 3rem;border-radius:0.5rem ;"
                                class="image" :src="scope.row.verThumbnail" :zoom-rate="1.2"
                                :preview-src-list="[scope.row.verThumbnail]" :initial-index="0" fit="cover" alt="" />
                        </div>
                    </div>
                    <div v-else>
                        无
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="tabName" label="名称" />
            <el-table-column prop="creationTime" label="创建时间" width="180">
                <template #default="scope">
                    {{ scope.row.creationTime }}
                </template>

            </el-table-column>

            <el-table-column prop="context" label="操作" width="300">
                <template #default="scope">
                    <div class="czbutton">
                        <label for="" style="color:#67b1ff" @click="edititem(scope.row)">编辑</label>
                        <label for="" style="color:#75d4a5">详情</label>
                        <label for="" style="color:#f78d8d" @click="delitem(scope.row.id)">删除</label>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background :total="total" v-model:current-page="currentPage2" v-model:page-size="pageSize2" />
        <!-- 添加数据模态框 -->
        <el-dialog v-model="dialogVisible" title="新增" width="30%" draggable align-center @close="closed">
            <el-form :model="form" label-width="120px" :rules="rules" ref="formEl">

                <!-- 图片上传 -->
                <el-form-item label="封面图" prop="verThumbnail">

                    <el-upload class="avatar-uploader" action="/dev-api/api/uploadimg/" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="form.verThumbnail" :src="form.verThumbnail" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="名称" prop="tabName">
                    <el-input v-model="form.tabName" placeholder="请填写" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogUpdate = false">取消</el-button>
                    <el-button type="primary" @click="onSubmit">
                        保存
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogUpdate" title="修改" width="30%" draggable align-center @close="allClose">
            <el-form :model="update" label-width="120px" :rules="ruled" ref="forms">
                <!-- 图片上传 -->
                <el-form-item label="封面图" prop="verThumbnail">
                    <el-upload class="avatar-uploader" action="/dev-api/api/uploadimg/" :show-file-list="false"
                        :on-success="updated" :before-upload="beforeAvatarUpload">
                        <img v-if="update.verThumbnail" :src="update.verThumbnail" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="名称" prop="tabName">
                    <el-input v-model="update.tabName" placeholder="请填写" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogUpdate = false">取消</el-button>
                    <el-button type="primary" @click="onUpdate">
                        保存
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts">
import { Search, RefreshLeft } from '@element-plus/icons-vue'
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { Plus } from '@element-plus/icons-vue'
import { fromPairs } from 'lodash';
import moment from "moment"
// 添加数据模态框

const dialogVisible = ref(false)
const all_delete = ref([])
const currentPage2 = ref(1)
const pageSize2 = ref(4)
const input = ref()
const total = ref(0)
const route = useRoute()
const forms = ref()
const formEl = ref()
// 添加的表单
const form = reactive({
    tabName: '',
    verThumbnail: "",
    painting_id: route.query.id
})
const rules = reactive({
    verThumbnail: [
        { required: true, message: '请选择图片', trigger: 'change' },
    ],
    tabName: [
        {
            required: true,
            message: '请输入名称',
            trigger: 'blur',
        },
    ]
})
const ruled = reactive({
    verThumbnail: [
        { required: true, message: '请选择图片', trigger: 'change' },
    ],
    tabName: [
        {
            required: true,
            message: '请输入名称',
            trigger: 'blur',
        },
    ]
})
const closed = () => {
    formEl.value.resetFields()
}
const allClose = () => {
    forms.value.resetFields()
}
const dialogUpdate = ref(false)
const you = ref(0)
const onUpdate = async () => {
    if (!forms.value) return
    await forms.value.validate((valid, fields) => {
        if (valid) {
            request.post('/api/painting/tabupd/', { id: you.value, ...update }).then(item => {
                dialogUpdate.value = false
                getlist()
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
const filterTime = (time) => {
    return moment(time).format('YYYY-MM-DD HH:mm:ss')
}
const updated = (data) => {
    console.log(data.path);

    update.verThumbnail = data.path
}
const update = reactive({
    tabName: '',
    verThumbnail: "",
    painting_id: route.query.id,
})
// add表单提交
const onSubmit = async () => {
    if (!formEl.value) return
    await formEl.value.validate((valid, fields) => {
        if (valid) {
            request.post('/api/painting/tabadd/', form).then(item => {
                form.tabName = ''
                form.verThumbnail = ''
                dialogVisible.value = false
                getlist()
            })
        } else {
            console.log('error submit!', fields)
        }
    })

}

const handleAvatarSuccess = (data) => {
    form.verThumbnail = data.path
}

const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

onMounted(() => {
    getlist()

})
const getlist = () => {
    let id = route.query.id
    request('/api/painting/tabshow/', { params: { 'id': id, 'page': currentPage2.value, 'page_size': 4, 'keyword': input.value } }).then(item => {
        newdata.value = item.tablist.map(item => {
            item.creationTime = filterTime(item.creationTime)
            return item
        })
        total.value = item.total
    })
}
watch(currentPage2, (news, olds) => {
    getlist()
})
// 多选 选中的数据数组
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
    all_delete.value = val.map(item => {
        return item.id
    })

}



// 所有数据

// 展示效果的数据
const newdata = ref([
    // {
    //     name: '王羲之粉丝',
    //     phone: '18888888888',
    //     context: 'app闪退app闪退阿斯达克警方卡拉胶打开房间啊阿克苏搭街坊卡森觉得警方打算离开房间奥斯陆扩大',
    //     imgs: [
    //         "https://img0.baidu.com/it/u=1273517628,1100314156&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1678899600&t=fa59a70f0172f705f52a4900407a6c8b",
    //         "https://img0.baidu.com/it/u=981218435,2998857702&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1678899600&t=46d09490b91be102f71435e81787e6ed",
    //     ],
    //     data: "2020-11-15 23:26:08",

    // },
])
// searchvalue
const searchvalue = () => {
    getlist()
}

// 重置按钮
const cz = () => {
    input.value = ""
    getlist()
}
// 删除所选数据
const del = () => {
    request.post('/api/painting/tabdelall/', { 'list': all_delete.value }).then(item => {
        getlist()
    })
}
const delitem = (id) => {
    request.delete('/api/painting/tabdel/?id=' + id).then(item => {
        getlist()
    })

}
// 编辑item
const edititem = (all) => {
    console.log(all);

    dialogUpdate.value = true
    update.tabName = all.tabName
    update.verThumbnail = all.verThumbnail
    you.value = all.id
    console.log(update);

    //    Object.assign(update,all)
}

// 时间戳过滤器
function filters(data) {
    let date = new Date(parseInt(data));
    let Year = date.getFullYear();
    let Moth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
    let Hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
    let Minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    let Sechond = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    let GMT = Year + '-' + Moth + '-' + Day + '   ' + Hour + ':' + Minute + ':' + Sechond;

    return GMT
}
</script>

<style>
.el-table .el-table__cell {
    z-index: auto !important;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}
</style>
<style scoped lang="scss">
.czbutton {
    label {
        display: inline-block;
        margin: 0 0.5rem;
    }
}

.el-pagination {
    margin: 2rem;
    float: right;
}

header {
    min-width: 50rem;

    .header_left {
        float: left;

    }

    .header_right {
        float: right;
        margin-bottom: 1rem;

        .el-input {
            margin-right: 1rem;
        }
    }

}


.demo-image__preview {
    width: 500px;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: flex-start;

    .image {
        margin: 0 0.5rem;
    }
}

.text {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}



.box-card {
    margin: 20px;
    border-radius: 20px;

}

.demo-image__error .image-slot {
    font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
    font-size: 30px;
}

.demo-image__error .el-image {
    width: 100%;
    height: 200px;
}




.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>